package net.sk.china.city.talk.config;

import net.sk.china.city.talk.constants.Constants;
import net.sk.china.city.talk.manager.CustomAccessDeniedHandler;
import net.sk.china.city.talk.manager.CustomAuthenticationProvider;
import net.sk.china.city.talk.manager.UnauthorizedHandler;
import net.sk.china.city.talk.service.impl.system.AdminDetailServiceImpl;
import net.sk.china.city.talk.token.JwtAuthenticationTokenFilter;
import net.sk.china.common.config.TalkConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;

/**
 * Security配置
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2018-2024 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2024/6/2 16:46
 * // +----------------------------------------------------------------------
 */

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class CloseSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private TalkConfig config;
    /**
     * 跨域过滤器
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 注册
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

    /**
     * token认证过滤器
     */
    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    /**
     * 认证失败处理类
     */
    @Bean
    public UnauthorizedHandler unauthorizedHandler() {
        return new UnauthorizedHandler();
    }

    /**
     * 鉴权失败处理类
     */
    @Bean
    public CustomAccessDeniedHandler accessDeniedHandler() {
        return new CustomAccessDeniedHandler();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new CustomAuthenticationProvider(new AdminDetailServiceImpl()));
    }

    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // CRSF禁用，因为不使用session
        http.cors().and().csrf().disable()
                // 认证失败处理类
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler())
                .accessDeniedHandler(accessDeniedHandler()).and()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                // 跨域预检请求
//            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 对于登录login 验证码captchaImage 和其他放行的目录 允许匿名访问"/citylife/front/**"
                .antMatchers("/login", "/validate/code").permitAll()
                .antMatchers("/getLoginPic").permitAll()
//                // 省节点 - 针对机构端开放、萍乡市电子政务共享数据交换平台、远程调用相关
//                .antMatchers("/remote/**", "/share/**", "/jxInstitution/**").permitAll()
                // 放行资源路径
                .antMatchers("/" + Constants.UPLOAD_TYPE_IMAGE + "/**").anonymous()
                .antMatchers("/" + Constants.UPLOAD_TYPE_FILE + "/**").anonymous()
                // 放行图片、文件上传
                .antMatchers("/upload/image", "/upload/file").permitAll()
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                .antMatchers("/v2/**", "/swagger-resources/**").permitAll()
                .antMatchers("/*/api-docs").anonymous()
                .antMatchers("/druid/**").anonymous()
                .antMatchers("/captcha/get", "/captcha/check").anonymous()
                .antMatchers("/notify/refund/**").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                // 防止iframe 造成跨域
                .headers().frameOptions().disable()
                .and()
                // // 启用X-Forwarded-For支持
                .headers().xssProtection();

        // 开启登录认证流程过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        // 添加CORS filter
        http.addFilterBefore(corsFilter(), JwtAuthenticationTokenFilter.class);
        http.addFilterBefore(corsFilter(), LogoutFilter.class);
    }


    /**
     * 跨域配置
     * @return {@code CorsConfiguration}
     */
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许任何域名
        corsConfiguration.addAllowedOrigin("*");
        // 允许任何头
        corsConfiguration.addAllowedHeader("*");
        // 允许任何方法
        corsConfiguration.addAllowedMethod("*");
        // 预检请求的缓存时间（秒），即在这个时间内，对于相同的跨域请求不会再预检了
        corsConfiguration.setMaxAge(18000L);
        // 允许cookies跨域
        corsConfiguration.setAllowCredentials(true);

        return corsConfiguration;
    }
}
